import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import 'rxjs/add/observable/concat';
import 'rxjs/add/operator/map';

import {NavController} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {DataQueryServiceProvider} from "@providers/data-query-service/data-query-service";

@Injectable()
export class AuthGuardProvider {
  isLoggedIn: boolean = false;
  page: string;
  navCtrl: NavController;
  private OpeningAnimation: boolean = true;//true 存在，false 不存在
  constructor(private storage: StorageProvider,
              private dataQueryService: DataQueryServiceProvider) {
  }

  login(user): Observable<boolean> {
    return Observable.create((observer) => {
      this.dataQueryService.login(user).subscribe(message => {
        let UserInfo = message.USER;
        UserInfo["isLoggedIn"] = true;
        this.storage.write('userInfo', UserInfo);
        this.saveAddressToLocalStorage().then(message => {
          observer.next(true);
          observer.complete();
        }, error => {
          this.loginError(error);
          observer.error(error);
        })
        //保存openId
        // this.dataQueryService.insertWXOpenId(UserInfo['PARTYID'], this.storage.read('openId'));
      }, error => {
        this.loginError(error);
        observer.error(error);
      });
    });
  }

  async saveAddressToLocalStorage() {
    let UserInfo = this.storage.read('userInfo');
    await this.queryUserFacility(UserInfo['PARTYID']).toPromise().then(message => {
      if (message != null) UserInfo["homeAddress"] = message;
    }, error => {
    });
    await this.queryShopAddress(UserInfo['PARTYID']).toPromise().then(message => {
      if (message != null) UserInfo["deliveryAddress"] = message;
    }, error => {
    });
    this.storage.write('userInfo', UserInfo);
    return true;
  }

  //查询用户默认地址
  queryUserFacility(PARTYID: any): Observable<any> {
    return this.dataQueryService.userfacility(PARTYID).map(value => {
      let homeAddress = {};
      if (value != "{}") {
        let address = value;
        homeAddress["id"] = address.FACILITYID;
        homeAddress["housesName"] = address.FAC_XQ;
        homeAddress["housesAddress"] = address.FAC_MC;
        homeAddress["IS_OWNER"] = address.IS_OWNER;
        homeAddress["BYNAME"] = address.BYNAME;
        homeAddress["IS_WYFDS"] = address.IS_WYFDS;
        homeAddress["IS_SFDS"] = address.IS_SFDS;
        homeAddress["IS_QTBD"] = address.IS_QTBD;
      }
      return homeAddress;
    });
  }

  //查询用户默认收获地址
  queryShopAddress(PARTYID: any): Observable<any> {
    return this.dataQueryService.getmorendizhi(PARTYID).map(value => {
      let shopAddress = value['data'][0];
      if (!shopAddress) {
        shopAddress = {};
      }
      return shopAddress;
    });
  }

  //登录失败
  loginError(message: any) {
    let UserInfo = {};
    this.storage.write('userInfo', UserInfo);
  }

  //判断是否登录
  checkLogin(page?: string, navCtrl?: NavController): boolean {
    if (this.isLogin()) {
      return true;
    }
    this.page = page;
    this.navCtrl = navCtrl;

    return false;
  }

  //判断登录类型 0：师傅 1:客户 2:提货员
  isEmployee(): number {
    let UserInfo = this.storage.read('userInfo');
    console.log("rylx:" + UserInfo["PAGE"][0]["ROLETYPEID"]);
    if (UserInfo && UserInfo["PAGE"][0]["ROLETYPEID"] == 'SAZYT') {
      return 0;
    } else if (UserInfo && UserInfo["PAGE"][0]["ROLETYPEID"] == 'KH') {
      return 1;
    } else {
      return 2;
    }
  }

  private isLogin(): boolean {
    let UserInfo = this.storage.read('userInfo');
    if (UserInfo) {
      if (UserInfo["isLoggedIn"]) {
        return true;
      }
    }
    return false;
  }

  //删除开场动画
  deleteTheOpeningAnimation() {
    if (!this.OpeningAnimation) return;
    this.OpeningAnimation = false;
    //app的z-index是0，层次高于入场的过渡动画。
    //添加了class：container-transform，设置它的层次高于app。
    //找到这个节点
    let _container = document.getElementsByClassName('container-transform');
    //删除节点
    if (_container && _container.length > 0) {
      _container[0].className += ' hidden';
      let _clear = setTimeout(() => {
        clearTimeout(_clear);
        _container[0].remove();
      }, 630);
    }
  }
}
